import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Input,
  Form,
  Tag,
  Modal,
  Select,
  message,
  Radio,
  DatePicker,
  Space,
} from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import BrandManagementStyle from './BrandManagement.module.css';
import Store from './../../store/index';
import { connect } from 'react-redux';
import * as Action from '../../store/actions/goods/action';
import ExportJsonExcel from 'js-export-excel';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

const mapStateToProps = state => {
  return {
    data: state.GoodsAttr.GoodsManage,
    GoodsGroup: state.GoodsAttr.options,
  };
};
const mapDispatchToProps = dispatch => {
  return {
    GoodsAdd: obj => {
      dispatch(Action.GoodsAddBtn(obj));
    },
    GoodsEdit: (id, obj) => {
      dispatch(Action.GoodsEditBtn(id, obj));
    },
    GoodsDel: id => {
      dispatch(Action.GoodsDelBtn(id));
    },
    GoodsSheL: (id, tags) => {
      dispatch(Action.GoodsSheLBtn(id, tags));
    },
  };
};
// 安装扩展jsx,在名称.jsx中输入rfc快速构建数据
const GoodsManagement = props => {
  const { GoodsEdit, GoodsDel, GoodsAdd, GoodsSheL } = props;
  const { confirm } = Modal;
  // 单选按钮
  const [value, setValue] = useState('');
  // 单选事件
  const onChange = e => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };
  // 当前时间
  // 添加
  const [addForm] = Form.useForm();
  // 修改
  const [editForm] = Form.useForm();
  // 打开关闭模态框
  const [open, setOpen] = useState(false);
  const [open2, setOpen2] = useState(false);
  // 表头
  const columns = [
    {
      title: '商品ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '原价',
      dataIndex: 'oPrice',
      key: 'oPrice',
    },
    {
      title: '商品分组',
      dataIndex: 'group',
      key: 'group',
    },
    {
      title: '当前销量',
      dataIndex: 'currentSales',
      key: 'currentSales',
    },
    {
      title: '剩余库存',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: '创建时间',
      dataIndex: 'cDate',
      key: 'cDate',
    },
    {
      title: '状态',
      key: 'tags',
      dataIndex: 'tags',
    },
    {
      title: '操作',
      key: 'action',
      render: row => (
        <div>
          <Button type='link' onClick={() => handleEdit(row)}>
            编辑
          </Button>
          <Button type='link' onClick={() => handleShelves(row)}>
            {row.tags === '上架中' ? '下架' : '上架'}
          </Button>
          <Button type='link' onClick={() => handleDel(row)}>
            删除
          </Button>
        </div>
      ),
    },
  ];
  // const [GoodsGroup, setGoodsGroup] = useState(Store.getState().GoodsAttr.options)
  const [data, setData] = useState(Store.getState().GoodsAttr.GoodsManage);
  // 获取当前时间
  const getCurrentTime = () => {
    var date = new Date();
    let Y = date.getFullYear() + '-';
    let M =
      (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ':';
    let m = date.getMinutes() + ':';
    let s = date.getSeconds();

    let currentTime = Y + M + D + h + m + s;
    // console.log(Y + M + D + h + m + s);
    // console.log('c', currentTime);
    return currentTime;
  };
  let [getTimes, setGetTimes] = useState(getCurrentTime());
  //#region 搜索
  const rangePresets = [
    {
      label: '今天',
      value: [dayjs().add(0, 'd'), dayjs()],
    },
    {
      label: '昨天',
      value: [dayjs().add(-1, 'd'), dayjs()],
    },
    {
      label: '近七天',
      value: [dayjs().add(-7, 'd'), dayjs()],
    },
  ];
  const [searchGroup, setSearchGroup] = useState();
  const [MName, setMName] = useState();
  const [MDate, setMDate] = useState('');
  const [MDate2, setMDate2] = useState('');
  const [MPrice, setMPrice] = useState();
  const [MPrice2, setMPrice2] = useState();
  // 商品名称输入框
  const MNameChange = v => {
    setMName(v.target.value.trim());
  };
  const MPriceChange = v => {
    setMPrice(v.target.value);
  };
  const MPriceChange2 = v => {
    setMPrice2(v.target.value);
  };
  //#region 搜索按钮
  const searchBtn = () => {
    console.log(MName);
    let list = [];
    clearTimeout(window.timer); //防抖查询
    window.timer = setTimeout(() => {
      props.data.forEach(el => {
        const condition =
          (!MName || el.name.includes(MName)) &&
          ((!MDate.$d && !MDate2.$d) ||
            (new Date(el.cDate) >= MDate.$d &&
              new Date(el.cDate) <= MDate2.$d)) &&
          (!searchGroup || el.group.includes(searchGroup)) &&
          ((!MPrice && !MPrice2) ||
            (el.price >= MPrice && el.price <= MPrice2));
        // const condition = (!MName || el.name.includes(MName))
        if (condition) {
          list.push(el);
        }
        setData(list);
      });
    }, 500);
  };
  //#endregion
  // 时间
  const onRangeChange = (dates, dateStrings) => {
    if (dates) {
      setMDate(dates[0]);
      setMDate2(dates[1]);
      // console.log('From: ', dates[0], ', to: ', dates[1]);
      console.log('From:1234 ', dateStrings[0], ', to: ', dateStrings[1]);
    } else {
      console.log('Clear');
    }
  };
  //#endregion
  // 导出
  const handleExportCurrentExcel = data => {
    let option = {};

    let sheetFilter = [
      'id',
      'name',
      'price',
      'oPrice',
      'group',
      'currentSales',
      'stock',
      'cDate',
    ];
    let dataTable = [];
    option.fileName = '商品管理';
    // data.map(el => {
    //     dataTable.push({
    //         'ID': el.id,
    //         '商品ID': el.gId,
    //         '商品': el.name,
    //         '价格': el.price,
    //         '原价': el.oPrice,
    //         '商品分组': el.group,
    //         '当前销量': el.currentSales,
    //         '剩余库存': el.stock,
    //         '创建时间': el.cDate,
    //     })
    // });
    option.datas = [
      {
        sheetData: data,
        sheetName: '商品管理',
        sheetFilter: sheetFilter,
        sheetHeader: [
          '商品ID',
          '商品',
          '价格',
          '原价',
          '商品分组',
          '当前销量',
          '剩余库存',
          '创建时间',
        ],
        columnWidths: [10, 10, 10, 10, 10, 10, 10, 10],
      },
    ];
    let toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  };
  // 删除当前行
  const handleDel = obj => {
    confirm({
      title: '你确定删除当前行吗',
      icon: <ExclamationCircleFilled />,
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        GoodsDel(obj.id);
        setData(
          JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsManage))
        );
        message.success('删除成功');
      },
      onCancel() {
        console.log('Cancel');
        message.error('删除失败');
      },
    });
  };
  //#region  新增
  // 新增打开模态框
  const openAdd = () => {
    addForm.setFieldsValue({
      id: data.length + 1,
      key: data.length + 1,
    });
    setOpen(true);
  };
  // 新增确定
  const handleOk = values => {
    console.log('Success:', values);
    GoodsAdd(values);
    setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsManage)));
    setOpen(false);
    addForm.resetFields();
    message.success('操作成功');
  };
  // 模态框取消按钮
  const onCannel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
    message.error('操作失败');
  };
  //#endregion

  //#region 编辑
  // 编辑当前行
  const handleEdit = obj => {
    let showData = {};
    data.forEach(element => {
      if (element.id === obj.id) {
        console.log('element', element);
        showData = JSON.parse(JSON.stringify(element));
      }
    });
    console.log('show', showData);
    editForm.setFieldsValue({ ...showData });
    setOpen2(true);
  };
  // 编辑模态框确定按钮
  const handleOk2 = values => {
    GoodsEdit(values.id, { ...values });
    setData(JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsManage)));
    setOpen2(false);
    message.success('操作成功');
    editForm.resetFields();
  };
  // 编辑模态框取消按钮
  const onCannel2 = () => {
    console.log('Clicked cancel button');
    setOpen2(false);
  };
  //#endregion

  // 上架下架
  const handleShelves = obj => {
    // console.log("obj", obj);
    // console.log("obj", obj.tags);
    confirm({
      title: `你确定${obj.tags === '上架中' ? '下架' : '上架'}吗`,
      icon: <ExclamationCircleFilled />,
      content: '',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        GoodsSheL(obj.id, `${obj.tags === '上架中' ? '已下架' : '上架中'}`);
        // data.forEach((el) => {
        //     if (el.id === obj.id && el.tags === "上架中") {
        //         el.tags === "已下架"
        //     }
        // })
        // setData(data)
        setData(
          JSON.parse(JSON.stringify(Store.getState().GoodsAttr.GoodsManage))
        );
        message.success('操作成功');
      },
      onCancel() {
        console.log('Cancel');
        message.error('操作失败');
      },
    });
  };

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
    message.warning('操作失败，请重试');
  };

  // 商品分组下拉
  const handleChange = value => {
    console.log(`selected ${value}`);
    setSearchGroup(value);
  };
  //#region
  // 表格分页
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 3,
    },
  });
  const fetchData = () => {
    setTableParams({
      ...tableParams,
      pagination: {
        ...tableParams.pagination,
        total: data.length,
      },
    });
  };
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams), data]);
  // 分页总条数的显示
  const showTotal = total => {
    return `总共${total}条`;
  };
  //表格页数变化
  const handleTablePageChange = (pagination, filters, sorter) => {
    setTableParams({
      pagination,
      filters,
      ...sorter,
    });
  };
  //#endregion
  return (
    <>
      <div className={BrandManagementStyle.title}>
        <div>
          <Button
            type='primary'
            onClick={openAdd}
            className={BrandManagementStyle.titleLeft}>
            新建商品
          </Button>
        </div>
      </div>
      <div className={BrandManagementStyle.goodsM}>
        <div className={BrandManagementStyle.goodsMF}>
          <label htmlFor='gName'>商品名称:</label>
          <Input
            placeholder='请输入'
            style={{ width: '180px', marginLeft: '10px' }}
            value={MName}
            onChange={MNameChange}
          />
          <label htmlFor='gName' style={{ marginLeft: '20px' }}>
            创建时间:
          </label>
          <RangePicker
            style={{ marginLeft: '20px' }}
            presets={rangePresets}
            showTime
            format='YYYY/MM/DD HH:mm:ss'
            onChange={onRangeChange}
          />
        </div>
        <div className={BrandManagementStyle.goodsMF}>
          <label htmlFor='gName'>商品分组:</label>
          <Select
            allowClear={true}
            style={{
              width: 120,
              marginLeft: '20px',
            }}
            placeholder={'请选择'}
            options={props.GoodsGroup}
            value={searchGroup}
            onChange={handleChange}
          />
          <label htmlFor='gName' style={{ marginLeft: '20px' }}>
            商品价格:
          </label>
          <Input
            placeholder='请输入'
            style={{ width: '180px', marginLeft: '10px' }}
            value={MPrice}
            onChange={MPriceChange}
          />
          <label htmlFor=''>-</label>
          <Input
            placeholder='请输入'
            style={{ width: '180px', marginLeft: '10px' }}
            value={MPrice2}
            onChange={MPriceChange2}
          />
        </div>
        <div className={BrandManagementStyle.goodsMF}>
          <Button type='primary' onClick={searchBtn}>
            搜索
          </Button>
          <Button
            className={BrandManagementStyle.goodsBtnR}
            onClick={() => {
              handleExportCurrentExcel(data);
            }}>
            导出
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        scroll={{ x: 1500 }}
        rowKey={record => record.id}
        pagination={{
          ...tableParams.pagination,
          showSizeChanger: true,
          showTotal,
          pageSizeOptions: [3, 5, 8, 10],
        }}
        onChange={handleTablePageChange}
      />
      <Modal title={'添加商品'} open={open} closable={false} footer={null}>
        <Form
          name='basic'
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={handleOk}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          form={addForm}>
          <Form.Item hidden name='id'>
            <Input />
          </Form.Item>
          <Form.Item hidden name='key'>
            <Input />
          </Form.Item>
          <Form.Item
            label='商品名称'
            name='name'
            placeholder='请输入'
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}>
            <Input placeholder='请输入' />
          </Form.Item>
          <Form.Item
            label='价格'
            name='price'
            placeholder='请输入'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label='原价'
            name='oPrice'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label='当前销量'
            name='currentSales'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label='库存'
            name='stock'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item label='商品分组' name='group'>
            <Select
              allowClear={true}
              style={{
                width: 120,
              }}
              options={props.GoodsGroup}
              onChange={handleChange}
            />
          </Form.Item>
          <Form.Item label='创建时间' name='cDate' initialValue={getTimes}>
            <Input placeholder='请输入' disabled />
          </Form.Item>
          <Form.Item name='tags'>
            <Radio.Group onChange={onChange}>
              <Radio value={'上架中'}>上架中</Radio>
              <Radio value={'已下架'}>已下架</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <div
              style={{
                width: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <Button
                type='primary'
                htmlType='submit'
                style={{ marginRight: '20px' }}>
                确认
              </Button>
              <Button type='primary' onClick={onCannel}>
                取消
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>

      {/*  编辑*/}
      <Modal title={'编辑'} open={open2} closable={false} footer={null}>
        <Form
          name='basic'
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={handleOk2}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
          form={editForm}>
          <Form.Item hidden name='id'>
            <Input />
          </Form.Item>
          <Form.Item hidden name='key'>
            <Input />
          </Form.Item>
          <Form.Item
            label='商品名称'
            name='name'
            placeholder='请输入'
            rules={[
              {
                required: true,
                message: '请输入',
              },
            ]}>
            <Input placeholder='请输入' />
          </Form.Item>
          <Form.Item
            label='价格'
            name='price'
            placeholder='请输入'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label='原价'
            name='oPrice'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label='当前销量'
            name='currentSales'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item
            label='库存'
            name='stock'
            rules={[
              {
                required: true,
              },
            ]}>
            <Input />
          </Form.Item>
          <Form.Item label='商品分组' name='group'>
            <Select
              allowClear={true}
              style={{
                width: 120,
              }}
              options={props.GoodsGroup}
              onChange={handleChange}
            />
          </Form.Item>
          <Form.Item label='创建时间' name='cDate'>
            <Input placeholder='请输入' disabled />
          </Form.Item>
          <Form.Item name='tags'>
            <Radio.Group onChange={onChange}>
              <Radio value={'上架中'}>上架中</Radio>
              <Radio value={'已下架'}>已下架</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <div
              style={{
                width: '100%',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <Button
                type='primary'
                htmlType='submit'
                style={{ marginRight: '20px' }}>
                确认
              </Button>
              <Button type='primary' onClick={onCannel2}>
                取消
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default connect(mapStateToProps, mapDispatchToProps)(GoodsManagement);
